package add_$20_Case_9_3;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class FileServer {

    public static void main(String[] args) throws IOException {
        
        ServerSocket serverSocket = new ServerSocket(10002);
        
        while(true) {
            
            // 监听客户端
            Socket socket = serverSocket.accept();
            
            // 开启一个线程
            new Thread(new ServerThread(socket)).start();
        }
    }
    
}
class ServerThread implements Runnable {
    
    private Socket socket;
    
    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        
        // 获取客户端的ip地址
        String ip = socket.getInetAddress().getHostAddress();
        
        // 记录文件的个数
        int count = 1;
        
        try {
            // 获取输入流，读取数据
            InputStream in = socket.getInputStream();
            
            // 创建一个File对象，封装/upload目录
            File parentFile = new File("upload");
            if (!parentFile.exists()) {
                
                // 不存在该目录则创建
                parentFile.mkdir();
            }
            System.out.println(parentFile.exists() + "\n" + parentFile.getAbsolutePath());
            
            // 创建一个File对象，封装/upload/ip(count).jpg文件
            File file = new File(parentFile, ip + "(" + count + ").jpg");
            while (file.exists()) {
                
                file = new File(parentFile, ip + "(" + count++ + ").jpg");
            }
            
            FileOutputStream fos = new FileOutputStream(file);
            
            // 读写操作
            byte[] buf = new byte[1024];
            int len = in.read(buf);
            while (len == -1) {
                fos.write(buf, 0, len);
            }
            
            // 给客户端进行响应
            OutputStream out = socket.getOutputStream();
            out.write("上传成功".getBytes());
            
            // 释放
            out.close();
            socket.close();
            
            
            // 创建
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
}